﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.Text;
using System.IO;

namespace NotesCommonProjects
{
    /// <summary>NOTES_002：Notes電腦財產管理AP to MIS Help API
    /// 接收QR code掃描機器人的指令, 轉拋給Notes的電腦財產管理AP</summary>

    public class CallComputerAssetNotesAgent : IHttpHandler
    {
        /*傳遞字串說明
        1.
        QRcode顯示出來的字串:
        "@CMD_SERVICE_ID=ComputerAsset&Action=CreateAsset&Computername=MI737N&uuid=9E7EC21C-364D-11DA-91EB-CAF81B4400E4$ipaddress=192.168.52.172&macaddress=2C-44-FD-23-BE-95&callee=203.69.132.110"

        2.
        用iSender掃描後, 機器人會將字串傳給【Notes電腦財產管理 to MIS Help API】(http://192.168.52.41/CallComputerAssetNotesAgent.ashx)

        API會將字串中的"@CMD_SERVICE_ID=ComputerAsset" 拿掉,

        加上Notes AP位置"http://tnotes03/Computer.nsf/ComputerAsset?OpenAgent",

        傳給Notes電腦財產管理AP的字串:
        "http://tnotes03/Computer.nsf/ComputerAsset?OpenAgent&Action=CreateAsset&Computername=MI737N&uuid=9E7EC21C-364D-11DA-91EB-CAF81B4400E4$ipaddress=192.168.52.172&macaddress=2C-44-FD-23-BE-95&callee=203.69.132.110"

        3.
        收到Notes電腦財產管理AP回傳的XML:
        <xml>
        <status>OK</status>
        <reason/>
        <openagent>OpenAgent</openagent>
        <action>CreateAsset</action>
        <computername>MI737N</computername>
        <uuid>192.168.52.172</uuid>
        <macaddress>2C-44-FD-23-BE-95</macaddress>
        <callee>203.69.132.110</callee>
        <notesdoc>
        explorer Notes://TNOTES03/48257BD000201CAB/D46DB30B9ADEA101482572A6000E79D
        </notesdoc>
        <username>CN=CH Chou/OU=MI/OU=T/O=CCP</username>
        </xml>

        將<notesdoc>標籤中的字串取出, 傳給MIS_Help的字串(所有字元皆為半形, 包含'&', '$', '空格'):
        NOTE_DOC&cmd=explorer Notes://TNOTES03/48257BD000201CAB/D46DB30B9ADEA101482572A6000E79D
        */

        const string ComputerNsfUrl = "http://tnotes03/Computer.nsf/ComputerAsset?OpenAgent";
        const string NotesUserName = "autoccpt";
        const string NotesUserPassword = "1111";
        string MisHelpParameterHeader = "NOTE_DOC&cmd=";

        public void ProcessRequest(HttpContext Context)
        {
            try
            {
                HttpRequest Request = Context.Request;

                //【01】取得QRCode掃描機器人API POST過來的參數
                string SipNum = Request.Form["SIP_Num"];
                string Command = Request.Form["Command"];

                //  過濾前
                //  @CMD_SERVICE_ID=ComputerAsset&Action=CreateAsset&Computername=MI737N&
                //  uuid=9E7EC21C-364D-11DA-91EB-CAF81B4400E4$ipaddress=192.168.52.172&
                //  macaddress=2C-44-FD-23-BE-95&callee=203.69.132.110

                //【02】過濾Command
                Command = Command.Substring(Command.IndexOf("&"));

                //  過濾後
                //  &Action=CreateAsset&Computername=MI737N&
                //  uuid=9E7EC21C-364D-11DA-91EB-CAF81B4400E4$ipaddress=192.168.52.172&
                //  macaddress=2C-44-FD-23-BE-95&callee=203.69.132.110

                //【03】GET tnotes03/電腦財產管理API(Computer.nsf)的web service
                string ComputerNsfRequestUrl = ComputerNsfUrl + Command;

                HttpWebRequest ComputerNsfRequest = (HttpWebRequest)WebRequest.Create(ComputerNsfRequestUrl);
                string AuthInfo = NotesUserName + ":" + NotesUserPassword;
                AuthInfo = Convert.ToBase64String(Encoding.ASCII.GetBytes(AuthInfo));
                ComputerNsfRequest.Headers.Add("Authorization", "Basic " + AuthInfo);   //使用Basic Authorization方式認證, 將帳號密碼夾在request header中
                ComputerNsfRequest.Method = WebRequestMethods.Http.Get;     //使用GET方法
                ComputerNsfRequest.AllowAutoRedirect = true;
                ComputerNsfRequest.Proxy = null;

                HttpWebResponse ComputerNsfResponse = (HttpWebResponse)ComputerNsfRequest.GetResponse();
                Stream Stream = ComputerNsfResponse.GetResponseStream();
                StreamReader StreamReader = new StreamReader(Stream);
                string XML = StreamReader.ReadToEnd();
                StreamReader.Dispose();
                Stream.Dispose();
                ComputerNsfResponse.Close();

                //【04】取得MIS Help要使用的外部參數
                int StartIndex = XML.IndexOf("<notesdoc>") + "<notesdoc>".Length;
                int EndIndex = XML.IndexOf("</notesdoc>");
                int Length = EndIndex - StartIndex;
                string MisHelpParameter = MisHelpParameterHeader + XML.Substring(StartIndex, Length);

                //【05】呼叫MIS_HELP
                //SipNum = "88238";     //傳給自己測試
                if (MSGKit.isHQMobileExt(SipNum))
                    MSGKit.SendTextHQAsync(SipNum, MisHelpParameter);

                //【06】寫入Log
                string LogContext = "【過濾後Command】 【" + Command + "】" +
                    "【NotesComputer.nsf回傳的XML】 【" + XML + "】" +
                    "【處理後要傳給MIS_HELP的字串】 【" + MisHelpParameter + "】";
                NotesCF.WriteLog(NotesCF.CallComputerAssetNotesAgentLogDir, LogContext);
            }
            catch (Exception ex)
            {
                //寫入Log
                string LogContext = "【呼叫失敗】 【" + ex.Message + "】";
                NotesCF.WriteLog(NotesCF.CallComputerAssetNotesAgentLogDir, LogContext);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}